package com.uinnova.product.eam.workable.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component("reSubmitToRejectMuilityInsertUserListener")
public class ReSubmitToRejectMuilityInsertUserListener implements ExecutionListener {

    @Autowired
    private transient HistoryService historyService;

    @Override
    public void notify(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .orderByHistoricTaskInstanceEndTime().asc().list()
                //过滤掉自动关闭任务
                .stream().filter(hTask -> !"MI_END".equals(hTask.getDeleteReason()))
                .filter(hTask -> hTask.getEndTime() != null).collect(Collectors.toList());
        log.info("list:{}", JSON.toJSONString(list));
        list.sort(Comparator.comparing(HistoricTaskInstance::getEndTime));
        String assignee = list.get(list.size()-1).getAssignee();

        Map<String, Object> variables = execution.getVariables();
        Object childVariable = variables.get("childVariable");
        if (childVariable != null) {
            log.info("子流程变量：{}", childVariable);
            if (childVariable instanceof String) {
                String jsonString = (String) childVariable;
                try {
                    JSONObject jsonObject = JSON.parseObject(jsonString);
                    jsonObject.put("rejectUsers", Arrays.asList(assignee));

                    variables.put("childVariable", jsonObject.toJSONString());
                    execution.setVariables(variables);
                } catch (Exception e) {
                    log.error("解析子流程变量异常", e);
                }
            }
        }
    }
}
